//
//  brandView.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/15.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "brandView.h"
#import "getCommonDataMode.h"
#import "pinyin.h"
#import "ChineseString.h"
#import "supplyViewButton.h"
@implementation brandView
@synthesize mainData,mainTable,isShow,tjData,LetterResultArr,indexArray,selectCity;
@synthesize dataArr = _dataArr ;
@synthesize rightArray;
@synthesize tjArray;
@synthesize selectString;
@synthesize sectionIndexView;
-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.mainData = [NSMutableDictionary dictionary];
        self.tjData = [NSMutableArray array];
        self.isShow = NO;
        self.indexArray = [NSMutableArray array];
        self.LetterResultArr = [NSMutableArray array];
        self.rightArray = [NSMutableArray array];
        self.tjArray = [NSMutableArray array];
        UITableView *tempTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH-17, frame.size.height)];
        tempTableView.delegate = self;
        tempTableView.dataSource = self;
        tempTableView.rowHeight = 100;
        tempTableView.sectionIndexBackgroundColor = [UIColor clearColor];
        self.mainTable = tempTableView;
        [self addSubview:self.mainTable];
        // 获得数据
        if ([self.mainTable respondsToSelector:@selector(setSeparatorInset:)])
        {
            [self.mainTable setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([self.mainTable respondsToSelector:@selector(setLayoutMargins:)])
        {
            [self.mainTable setLayoutMargins:UIEdgeInsetsZero];
        }
//        [ self getSectionAndCellData ];
//        [ self createTableView ];
        self.sectionIndexView = [[UIView alloc] initWithFrame:CGRectMake(SWIDTH - 17, 0, 17, frame.size.height)];
        self.sectionIndexView.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.sectionIndexView];
    }
    return self;
}

#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = [indexArray objectAtIndex:section];
    return key;
}
#pragma mark - Section header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SWIDTH-17, 20)];
    lab.backgroundColor = UIColorFromRGB(0xf7f7f7);
    lab.text = [NSString stringWithFormat:@"  %@",[indexArray objectAtIndex:section]];
    lab.textColor = GRAYColor;
    lab.font = [UIFont systemFontOfSize:13];
    return lab;
}
#pragma mark - row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        int height = 0;
        for (int i = 0; i <[self.tjData count]; i++) {
            tj_brandsModel *brandModel = [self.tjData objectAtIndex:i];
            NSString *nameStr = brandModel.name;
            supplyViewButton *vButton = nil;
            int BtnW = (SWIDTH/3);
            int BtnH = 44;
            vButton = [self returnButtonWithFrame:CGRectMake( BtnW * (i%3) , BtnH *(i/3), BtnW, BtnH ) withTag:i+10 withTitle:nameStr];
            vButton.brand = brandModel;
            if ([selectCity isEqualToString:nameStr]) {
                [vButton.button setSelected:YES];
                vButton.button.titleLabel.highlightedTextColor = BLUEColor;
            }
            height = BtnH *(i/3) + 65;
        }
        return height;
    }
    return 44;
}

#pragma mark -
#pragma mark Table View Data Source Methods
#pragma mark -设置右方表格的索引数组
//-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{   
//    return rightArray;
//}
#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSLog(@"title===%@",title);
    return index;
}

#pragma mark -允许数据源告知必须加载到Table View中的表的Section数。
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [indexArray count];
}
#pragma mark -设置表格的行数为数组的元素个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section ==0) {
        return 1;
    }else{
        return [[self.LetterResultArr objectAtIndex:section] count];
    }
}

#pragma mark -每一行的内容为数组相应索引的值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellId = [NSString stringWithFormat:@"cellid%ld",(long)indexPath.row];
    static NSString *tableCell =@"Cell";
    UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:tableCell];
    UITableViewCell* cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
    
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId] ;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if (indexPath.section==0) {
        if (!cell1) {
            cell1 =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCell];
            [cell1 setSelectionStyle:0];
        }
        if ([tjArray count]!= 0) {
            for (int i = 0; i < [tjArray count]; i++) {
                supplyViewButton *button = [tjArray objectAtIndex:i];
                [button removeFromSuperview];
                button = nil;
                [tjArray removeObjectAtIndex:i];
            }
        }
        for (int i = 0; i <[self.tjData count]; i++) {
            tj_brandsModel *brandModel = [self.tjData objectAtIndex:i];
            NSString *nameStr = brandModel.name;
            supplyViewButton *vButton = nil;
            int BtnW = (self.mainTable.frame.size.width/3);
            int BtnH = 44;
            vButton = [self returnButtonWithFrame:CGRectMake( BtnW * (i%3) ,10+ BtnH *(i/3), BtnW, BtnH ) withTag:i+10 withTitle:nameStr];
            vButton.brand = brandModel;
            if ([selectString isEqualToString:nameStr]) {
                [vButton.button setSelected:YES];
                [vButton.button setTitleColor:BLUEColor forState:0];
                vButton.button.layer.borderColor = [BLUEColor CGColor];
            }
            [vButton.button addTarget:self action:@selector(tjButotnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.tjArray addObject:vButton];
            [cell1 addSubview:vButton];
        }
        return cell1;
    }else{
        tj_brandsModel *brandModel = [[self.LetterResultArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        cell.textLabel.text = brandModel.name;
        cell.textLabel.textColor = GRAYColor;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
        if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
            // 取消标记
            cell.accessoryType  = UITableViewCellAccessoryNone;
        }
        if ([self.selectString isEqualToString:brandModel.name]) {
            cell.textLabel.textColor = UIColorFromRGB(0x2578c3);
            cell.accessoryType  = UITableViewCellAccessoryCheckmark;
        }
        if ([self.selectString isEqualToString:@"品牌"]) {
            if ([brandModel.name isEqualToString:@"全部"]) {
                cell.textLabel.textColor = UIColorFromRGB(0x2578c3);
                cell.accessoryType  = UITableViewCellAccessoryCheckmark;
            }
        }
        return cell;
    }
}

-(void)tjButotnClick:(supplyViewButton *)sender{
    tj_brandsModel *brandModel = [self.tjData objectAtIndex:sender.tag - 10];
    [self.delegate selectBrand:brandModel];
}
#pragma mark - Select内容为数组相应索引的值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section!=0) {
        NSLog(@"选择中");
        NSArray *arr = [self.LetterResultArr objectAtIndex:indexPath.section];
        tj_brandsModel *brandModel = [arr objectAtIndex:indexPath.row];
        [self.delegate selectBrand:brandModel];
    }
}


-(void)createTJ_BrandView{
    UILabel *tempLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 22)];
    tempLab.text = @"品牌推荐";
    [self addSubview:tempLab];
    for (int i = 0; i <[self.tjData count]; i++) {
        tj_brandsModel * model = [self.tjData objectAtIndex:i];
        UILabel *lab = [self createLabFrame:CGRectMake((SWIDTH/3)*i, 0, SWIDTH/3, 43)  title:model.name titleColor:UIColorFromRGB(0x353535) tag:10+i];
        [self addSubview:lab];
    }
}
-(UILabel *)createLabFrame:(CGRect)frame
                title:(NSString *)title
           titleColor:(UIColor *)color
                  tag:(NSInteger)tag{
    UILabel *lab = [[UILabel alloc]initWithFrame:frame];
    lab.backgroundColor = [UIColor clearColor];
    lab.textColor = color;
    lab.text = title;
    return lab;
}
-(void)reloadView{
    NSArray* arr1 = [self.mainData allKeys];
    arr1 = [arr1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result==NSOrderedDescending;
    }];
    for (int i = 0; i <[arr1 count]; i++) {
        NSString *bigKey = [[arr1 objectAtIndex:i] uppercaseString];
        NSString *key = [arr1 objectAtIndex:i];
        [self.LetterResultArr addObject:[self.mainData objectForKey:key]];
        [self.indexArray addObject:bigKey];
        [self.rightArray addObject:bigKey];
    }
    [self.indexArray insertObject:@"#" atIndex:0];
    [self.rightArray insertObject:@"#" atIndex:0];
    tj_brandsModel *model = [[tj_brandsModel alloc]init];
    model.brand_id = @"";
    model.name = @"全部";
    NSArray *arr = [NSArray arrayWithObject:model];
    [self.LetterResultArr insertObject:arr atIndex:0];
    [self.indexArray insertObject:@"品牌推荐" atIndex:0];
    NSArray *arr2 = [NSArray arrayWithObject:@"测试"];
    [self.LetterResultArr insertObject:arr2 atIndex:0];
    
    for (UIView *item in self.sectionIndexView.subviews) {
        [item removeFromSuperview];
    }
    CGRect indexRect = self.sectionIndexView.frame;
    NSInteger indexNumber = [self.rightArray count];
    float spaceNumber = (indexRect.size.height-(16*indexNumber))/(indexNumber +1);
    int height = 0;
    for (int num = 0; num < indexNumber; num++) {
        UIButton *indexButton = [UIButton buttonWithType:UIButtonTypeCustom];
        indexButton.tag = num+300;
        [indexButton setTitle:[self.rightArray objectAtIndex:num] forState:UIControlStateNormal];
        indexButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [indexButton setTitleColor:UIColorFromRGB(0x007aff) forState:UIControlStateNormal];
        indexButton.frame = CGRectMake(0, spaceNumber+(spaceNumber + 12)*num, 17, 20);
        [indexButton addTarget:self action:@selector(toSectionIndex:) forControlEvents:UIControlEventTouchUpInside];
        height = indexButton.frame.size.height+indexButton.frame.origin.y;
        [self.sectionIndexView addSubview:indexButton];
    }
    self.sectionIndexView.frame = CGRectMake(SWIDTH - 17, (self.frame.size.height - height)/2, 17, height);
    [self.mainTable reloadData];
}
-(void)toSectionIndex:(UIButton *)sender
{
    NSIndexPath *cellIndex = [NSIndexPath indexPathForRow:0 inSection:sender.tag-299];
    CGRect cellPositon = [self.mainTable rectForRowAtIndexPath:cellIndex];
    float topPosition = cellPositon.origin.y;
    if (self.mainTable.contentSize.height - topPosition < self.frame.size.height) {
        [self.mainTable setContentOffset:CGPointMake(0, self.mainTable.contentSize.height - self.frame.size.height) animated:YES];
        return;
    }
    [self.mainTable setContentOffset:CGPointMake(0, topPosition) animated:YES];
}
-(supplyViewButton *)returnButtonWithFrame:(CGRect)frame  withTag:(int)Tag withTitle:(NSString *)title{
    supplyViewButton *vButton = [[supplyViewButton alloc]initWithFrame:frame];
    [vButton.button setTitle:title forState:0];
    [vButton.button setTitleColor:GRAYColor forState:UIControlStateNormal];
    [vButton.button setFrame:CGRectMake((frame.size.width - 70)/2, 5, 70, 34)];
    vButton.button.titleLabel.font = [UIFont systemFontOfSize:12];
    [vButton.button setTitleColor:UIColorFromRGB(0x2578c3) forState:UIControlStateSelected];
    [vButton.button setBackgroundColor:[UIColor clearColor]];
    Radio(vButton.button, grayColor);
    [vButton.button setSelected:NO];
    vButton.button.tag = Tag;
//    [vButton.button addTarget:self action:@selector(selectCity:) forControlEvents:UIControlEventTouchUpInside];
    return vButton;
}
-(void)selectCity:(UIButton *)sender{
    for (int i = 0; i < [tjArray count]; i++) {
        supplyViewButton *vBtton = [tjArray objectAtIndex:i];
        vBtton.button.selected = NO;
        vBtton.button.titleLabel.textColor= GRAYColor;
    }
    if (sender.selected == NO) {
        sender.selected = YES;
        sender.titleLabel.highlightedTextColor = UIColorFromRGB(0x2578c3);
    }else{
        sender.selected = NO;
        sender.titleLabel.highlightedTextColor = GRAYColor;
    }
    tj_brandsModel *brandModel = [self.tjData objectAtIndex:sender.tag - 10];

    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(selectBrand:)]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:sender.titleLabel.text forKey:@"brandName"];
        [self.delegate selectBrand:brandModel];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
